# -*- coding: ISO-8859-1 -*-
import wx
import os, sys
from frmSplash import splashForm
from frmSettings import settingsForm
import BaseHTTPServer, select, signal, socket, SocketServer, urlparse
import re
from proxyserver import *

class mainForm(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "", wx.DefaultPosition)
        self.tskic = mainTaskIcon(self)
        self.cfg = wx.Config('pyddler')
        self.menubar = mainMenuBar()
        self.splitter1 = wx.SplitterWindow(self, -1, style=wx.SP_3D)
        self.notebook=mainBook(self.splitter1)
        #self.notebook.AddPage(None,"Seite 1")
        #self.tree = mainTree(self.splitter1)
        #self.panel1 = wx.Panel(self.splitter1, -1)
        #self.display = wx.StaticText(self.panel1, -1, 'test',(10,10), style=wx.ALIGN_CENTRE)
        self.splash=splashForm()
        self.settings=settingsForm(self.cfg)
        self.statusbar = self.CreateStatusBar()
        self.list=mainList(self.splitter1)
        self.server=PyddlerProxyServer(self.OnRequest)
        #self.server.onRequest=self.OnRequest
        

        self.__load_config()
        self.__set_properties()
        self.__set_bindings()
        self.__do_layout()

    def __set_properties(self):
        self.SetTitle("Pyddler")
        self.SetIcon(wx.Icon('icons/multimedia.png', wx.BITMAP_TYPE_PNG))
        self.SetMenuBar(self.menubar)
        self.splitter1.SplitVertically(self.list,self.notebook)

    def __set_bindings(self):
        self.Bind(wx.EVT_MENU, self.OnOpen, id=101)
        self.Bind(wx.EVT_MENU, self.OnSave, id=102)
        self.Bind(wx.EVT_MENU, self.OnQuit, id=105)
        self.Bind(wx.EVT_MENU, self.OnAbout, id=410)
        self.Bind(wx.EVT_MENU, self.OnSettings, id=210)
        self.Bind(wx.EVT_TOOL, self.OnNew, id=1)
        self.Bind(wx.EVT_TOOL, self.OnOpen, id=2)
        self.Bind(wx.EVT_TOOL, self.OnSave, id=3)
        self.Bind(wx.EVT_TOOL, self.OnQuit, id=4)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        #self.tree.Bind(wx.EVT_TREE_SEL_CHANGED,self.OnSelChanged,id=1002)

    def __do_layout(self):
        self.Layout()

    def __load_config(self):
        #Hoehe und Breite
        if self.cfg.Exists("width") and self.cfg.Exists("height"):
            w,h=self.cfg.ReadInt("width"), self.cfg.ReadInt("height")
        else:
            (w,h)=(800,600)
        self.SetSize(wx.Size(w,h))
        #Position
        if self.cfg.Exists("x") and self.cfg.Exists("x"):
            x,y=self.cfg.ReadInt("x"), self.cfg.ReadInt("y")
            self.SetPosition(wx.Point(x,y))
        else:
            self.Centre()
        #Breite des Trees
        if self.cfg.Exists("treewidth"):
            treewidth=self.cfg.ReadInt("treewidth")
        else:
            treewidth=200
        self.splitter1.SetSashPosition(treewidth)

    def __save_config(self):
        #Hoehe und Breite
        (w,h)=self.GetSize()
        self.cfg.WriteInt("width",w)
        self.cfg.WriteInt("height",h)
        #Position
        (x,y)=self.GetPosition()
        self.cfg.WriteInt("x",x)
        self.cfg.WriteInt("y",y)
        #Breite des Trees
        x=self.splitter1.GetSashPosition()
        self.cfg.WriteInt("treewidth",x)
        self.cfg.Flush()
        
    def OnRequest(self,req):
        print "mainForm::OnRequest"
        num= self.list.GetItemCount()
        print(req)
        self.list.InsertStringItem(num,req.gethostname())

    def OnClose(self,event):
        self.__save_config()
        self.tskic.Destroy()
        self.server.stop()
        self.server=None
        self.Destroy()
        wx.Exit()

    def OnQuit(self, event):
        self.Close()

    def OnNew(self,event):
        self.statusbar.SetStatusText('New Command')

    def OnOpen(self,event):
        self.statusbar.SetStatusText('gestartet...')
        self.server.start()
        '''
        self.statusbar.SetStatusText('Open Command')
        dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.*", wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            mypath = os.path.basename(path)
            self.SetStatusText("You selected: %s" % mypath)
        dlg.Destroy()
        '''

    def OnSave(self,event):
        self.statusbar.SetStatusText('gestoppt...')
        self.server.stop()
        '''
        self.statusbar.SetStatusText('Save Command')
        dlg = wx.FileDialog(self, "Save a file", os.getcwd(), "", "*.*", wx.SAVE)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            mypath = os.path.basename(path)
            self.SetStatusText("You selected: %s" % mypath)
        dlg.Destroy()
        '''

    def OnAbout(self,event):
        self.statusbar.SetStatusText('OnAbout')
        self.splash.ShowModal()

    def OnSettings(self,event):
        self.settings.ShowModal()
        
    def OnSelChanged(self,event):
        item = event.GetItem()
        text = self.tree.GetItemText(item)
        self.statusbar.SetStatusText(text)

class mainMenuBar(wx.MenuBar):
    def __init__(self):
        wx.MenuBar.__init__(self)
        file = wx.Menu()
        edit = wx.Menu()
        help = wx.Menu()

        open = wx.MenuItem(file, 101, '&Oeffnen\tCtrl+O', 'Oeffnen')
        open.SetBitmap(wx.Image('icons/document-open.png',wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        save=wx.MenuItem(file, 102, '&Speichern\tCtrl+S', 'Speichern')
        save.SetBitmap(wx.Image('icons/document-save.png',wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        quit = wx.MenuItem(file, 105, '&Beenden\tCtrl+Q', 'Programm beenden')
        quit.SetBitmap(wx.Image('icons/system-log-out.png',wx.BITMAP_TYPE_PNG).ConvertToBitmap())

        settings=wx.MenuItem(edit,210,"&Einstellungen","Enstellungen")
        settings.SetBitmap(wx.Image('icons/preferences-system.png',wx.BITMAP_TYPE_PNG).ConvertToBitmap())

        about=wx.MenuItem(help,410,"Ueber Pyddler","")

        file.AppendItem(open)
        file.AppendItem(save)
        file.AppendSeparator()
        file.AppendItem(quit)

        edit.AppendItem(settings)

        help.AppendItem(about)

        self.Append(file, '&Datei')
        self.Append(edit, '&Bearbeiten')
        self.Append(help, '&Hilfe')

class mainToolBar(wx.ToolBar):
    def __init__(self, *args, **kwargs):
        wx.ToolBar.__init__(self, *args, **kwargs)
        self.AddSimpleTool(1, wx.Image('icons/document-new.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'New', '')
        self.AddSimpleTool(2, wx.Image('icons/document-open.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Open', '')
        self.AddSimpleTool(3, wx.Image('icons/document-save.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Save', '')
        self.AddSeparator()
        self.AddSimpleTool(4, wx.Image('icons/system-log-out.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Exit', '')
        self.Realize()

class mainTree(wx.TreeCtrl):
    def __init__(self,parent=None):
        wx.TreeCtrl.__init__(self,parent,1002)
        self.il=mainImageList()
        self.root = self.AddRoot('Pythia')
        self.os = self.AppendItem(self.root, "Player",self.il.multimedia_idx)
        self.pl = self.AppendItem(self.root, "CD",self.il.optical_idx)
        self.tk = self.AppendItem(self.root, "Playlist")
        self.__set_properties()
        #self.__do_layout()
        
    def __set_properties(self):
        self.SetWindowStyle(wx.TR_HAS_BUTTONS|wx.TR_FULL_ROW_HIGHLIGHT|wx.TR_NO_LINES)
        self.AssignImageList(self.il)
    #def __do_layout(self):
        #self.root.ExpandAll()
        
class mainList(wx.ListCtrl):
    def __init__(self,parent=None):
        wx.ListCtrl.__init__(self,parent,1909,style=wx.LC_REPORT)
        self.InsertColumn(0,"#")
        self.InsertColumn(1,"Result")
        self.InsertColumn(2,"Host")
        self.InsertColumn(3,"URL")
        
class mainBook(wx.Notebook):
    def __init__(self,parent=None):
        wx.Notebook.__init__(self,parent,1919)
        self.performance_panel=wx.Panel(self)
        self.inspector_panel=wx.Panel(self)
        self.builder_panel=wx.Panel(self)
        self.AddPage(self.performance_panel,"Performance Statistics")
        self.AddPage(self.inspector_panel,"Session Inspector")
        self.AddPage(self.builder_panel,"Request Builder")
        
class mainImageList(wx.ImageList):
    def __init__(self):
        wx.ImageList.__init__(self,16,16)
        self.multimedia_idx=self.AddIcon(wx.Icon('icons/multimedia.png', wx.BITMAP_TYPE_PNG))
        self.optical_idx=self.AddIcon(wx.Icon('icons/media-optical.png', wx.BITMAP_TYPE_PNG))

class mainTaskIcon(wx.TaskBarIcon):
    def __init__(self, frame):
        wx.TaskBarIcon.__init__(self)

        self.frame = frame
        self.SetIcon(wx.Icon('icons/multimedia.png', wx.BITMAP_TYPE_PNG), 'Pyddler')
        self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, id=1)
        self.Bind(wx.EVT_MENU, self.OnTaskBarDeactivate, id=2)
        self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=3)

    def CreatePopupMenu(self):
        menu = wx.Menu()
        menu.Append(1, 'Show')
        menu.Append(2, 'Hide')
        menu.Append(3, 'Close')
        return menu

    def OnTaskBarClose(self, event):
        self.frame.Close()

    def OnTaskBarActivate(self, event):
        if not self.frame.IsShown():
            self.frame.Show()

    def OnTaskBarDeactivate(self, event):
        if self.frame.IsShown():
            self.frame.Hide()


